package com.android.openapp.services;

import java.util.ArrayList;
import java.util.List;

import com.socrata.api.HttpConnection;
import com.socrata.api.RequestException;
import com.socrata.api.Response;
import com.socrata.data.View;
import com.socrata.data.View.Column;


import data.Place;

import data.Museo;
import data.Ostello;


import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

/**
 * Servizio che sta dietro all'Activity
 * si occupa di lanciare i thread del download, recuperare la posizione tramite GPS,
 * recuperare le impostazioni, ...
 * @author Simone Panza
 * 
 *
 */

public class Controller extends Service {
	/**
	 * @author Allieri Tommaso
	 * Parametri connessione e istanza di connessione
	 */
	private static String domain="dati.lombardia.it";
	private static String user="tommy.evo@hotmail.com";
	private static String password="d4c3b2a1";
	private static String apptoken="z2eM5pVNIh71ovXSX426RI2un";
	
	public static HttpConnection c=new HttpConnection(domain, user, password, apptoken);
	/**
	 * Fine parametri di connessione
	 */
	
	private ControllerBinder mBinder;
	
	@Override
	public void onCreate() {
		super.onCreate();
		mBinder = new ControllerBinder();
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}
	
	/**
	 * il binder implementa l'interfaccia che viene vista dall'Activity
	 * deve contenere metodi utili alla Activity
	 * @author Simone Panza
	 *
	 */
	public class ControllerBinder extends Binder implements ControllerServiceInterface{
		
		
		/**
		 * @author Allieri Tommaso
		 * @param distance
		 * da finire implementanto la posizione GPS
		 */
	
		@Override
		public ArrayList<Place> getNearPlaces(int distance) {
			// TODO Auto-generated method stub
			ArrayList<Place> list=new ArrayList<Place>();
			
    		String lat="45.8964306";
    		String lng="9.6545868";
    		String range=Integer.toString(distance);
    		/**
    		 * 
    		 * lat= 45.8964306
    		 * lng= 9.6545868
    		 * range= 10
    		 * 
    		 * 9897725
    		 * */
    		
    		for(int i=0;i<Place.datasetM.length;i++){
    			//Ricerca colonna di tipo 'Place'
    			Column lag=getCol(Place.listmetadati.get(i));
    			//Log.d("TEST", lag.getName());

    			String json =  "{query:{'originalViewId':"+Place.datasetM[i].toLowerCase()+",'name':"+Place.datasetM[i].toLowerCase()+","+
    					"'query':{" +
    					"'filterCondition':{" +
    							"'type':'operator'," +
    							"'value':'AND'," +
    							"'children':[" +
    							"{" +
    							"'type':'operator'," +
    							"'value':'WITHIN_CIRCLE'," +
    							"'children':[" +
    							"{'columnId':"+Integer.toString(lag.getId())+"," +
    							"'type':'column'" +
    							"}," +
    							"{" +
    							"'type':'literal'," +
    							"'value':"+lat+
    							"}," +
    							"{" +
    							"'type':'literal'," +
    							"'value':"+lng+
    							"}," +
    							"{" +
    							"'type':'literal'," +
    							"'value':"+range+
    							"}" +
    							"]" +
    							"}" +
    							"]" +
    							"}" +
    							"}" +
    							"}" +
    							"}";
    			//Log.d("fase2",json);
    			
    			//Log.d("fase2","ok");
    			Response r=c.post("https://dati.lombardia.it/api/views/INLINE/rows.json?method=getRows&start=0&length=100",json);
    			try {
    				Thread.sleep(1*1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			
    			//Log.d("fase2",Integer.toString(r.status));
    			
    			
    			try {
    				
    				List<View.Row> row1 = Place.listmetadati.get(i).getRows(r);
    				Log.d("fase2",Integer.toString(row1.size()));
    				/*
    				if(row1==null)
    					Log.d("fase2", "NULL");
    					*/
    				Log.d("fase2", Place.listmetadati.get(i).getId());
    				//Log.d("fase2", row1.get(0).getId());
    				Place loc = null;
    				for(View.Row temp : row1){
    					
    					switch(i){
        				case 0: loc=new Museo(temp);
        						Log.d("Museo",loc.getDenominazione());
        						break;
        				case 1: loc=new Ostello(temp);
        						break;
        					
        				}
    					list.add(loc);
    					//loc.addPlace(loc);
    					
    				}
    				
    				
    				//loc.addListMuseo(row1);
    				//Row row2=row1.get(0);
    				//Place m=new Museo(row2);
    				//m.addPlace(m);
    				
    				//m.toString();
    				
    				
    			} catch (RequestException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		
    		}
			ArrayList<String> mList = new ArrayList<String>();
			mList.add("seriate");
			mList.add("pedrengo");
			
			return list;
		}

		@Override
		public ArrayList<String> searchForPlaces(String searchString) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void saveSettings(Bundle b) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void loadSettings() {
			// TODO Auto-generated method stub
			
		}
		private Column getCol(View v){
			List<Column> cl=v.getColumns();
			for(Column m : cl){
				if(m.getDataTypeName().equals("location")){
					return m;
				}
			}
			return null;
		}
		
		
	}
	
}
